package org.bob.learn.common.util;

import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.Pageable;

import java.util.Objects;

public enum SQLMapper {

    INSTANCE;

    public static String map(final String baseSql, final Object criteria) {
        StringBuilder sb = new StringBuilder();
        sb.append(baseSql);
        BeanMap.create(criteria).forEach((key, value) ->{
            if(!Objects.equals(key.toString(), "paged") && !Objects.equals(key.toString(), "pageSize") && !Objects.equals(key.toString(), "pageNumber") && !Objects.equals(key.toString(), "offset") && value!=null){
                sb.append(" AND ").append(key.toString()).append("=");
                if(value instanceof String){
                    sb.append("'").append(value).append("'");
                }else if(value instanceof Long){
                    sb.append(value);
                }else if(value instanceof Integer){
                    sb.append(value);
                }else if(value instanceof Byte){
                    sb.append(value);
                }
            }

        });
        if(criteria instanceof Pageable && ((Pageable) criteria).isPaged()){
            sb.append(" LIMIT ").append(((Pageable)criteria).getPageSize()).append(" OFFSET ").append(((Pageable)criteria).getOffset());
        }
        return sb.toString();
    }
}
